package com.itheima.wechatweb;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @outhor
 * @date 2020/2/6 15:26
 */

@RequestMapping("login")
@RestController
public class loginController {

    @Reference
    private MemberService memberService;

    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("check")
    public Result check(@RequestBody Map map, HttpServletRequest request){
        //1.校验短信验证码
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String redisCode = redisUtil.get(telephone + RedisConstant.SENDTYPE_LOGIN);
        if (redisCode==null||!redisCode.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //2.根据手机号查询会员是否存在,如果不存在注册会员
        Member member =memberService.findByTelephone(telephone);
        if (member==null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);
        }

        //3.0.将会员信息保存到session中(无法解决多态服务器同时拥有该session,可以用redis+token来解决见下面3.1)
//        request.getSession().setAttribute("member",member);

        //3.1.将会员信息保存在redis中
        String token = UUID.randomUUID().toString();
        redisUtil.setex(token,JSON.toJSONString(member),60*60*24);

        return new Result(true, MessageConstant.LOGIN_SUCCESS,token);
    }
}
